//index.js
const app = getApp()
Page({
  data: {
    aid:'',
    phoneNumber:'',
    lng:'',
    lat:'',
    shareimg:'',
    shareimg2:'',
    detailimgs:[],
    qrcodeurl:'',
    resdata:[],
    img: "/activity/images/tel.png",
    wechat: "/activity/images/wechat.png",
    xiazai: "/activity/images/download.png",
    share:"/activity/images/share.png",
    maskHidden: false,
    imagePath:'',
    nickName: "",
    headImg: '',
    avatarUrl: './user-unlogin.png',
    backgroundTest: '',
    background: [],
    texts:["建德云漫松间 | 688元抢樱飞/枫舞/修竹/杏会2天1晚。应季采摘+双人早餐+趣味体验。"],
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    interval: 2000,
    duration: 500,
    circular:true,
    width:0,
    height:0,
    items:[
      {value: '0', name: '经典单晚套餐', surplus:'37',activity:'688',price:'1180',checked: 'true'},
      {value: '1', name: '豪华单晚套餐',surplus:'47',activity:'788',price:'1380'},
      {value: '2', name: '经典双晚套餐',surplus:'57',activity:'1288',price:'1680'},
      {value: '3', name: '豪华双晚套餐',surplus:'66',activity:'1488',price:'1980'},
    ],
    showModalStatus:false,
    shareModalStatus:false,
    userinfo:false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide: false,
    userInfo: {},
    hasUserInfo: false,
    logged: false,
    takeSession: false,
    canvas: true,
    requestResult: '',
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl'), // 如需尝试获取用户信息可改为false
  },
 

 
friends:function(e){
  let that = this
  /*wx.showToast({
    title: '点击右上角"..."选择【分享到朋友圈】',
    icon: 'none',
    duration: 2000
  });*/
  that.onShareTimeline()
},
  onLoad: function(query) {
    const scene = decodeURIComponent(query.scene)
    console.log("activity")
    console.log(scene)
    console.log("activity")
    var that = this;
    if(scene){
      that.aid = scene
      that.getdetail()
    }

    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });



  },


  getdetail:function(){
    console.log("获取活动详情")
    var that = this;
 
    wx.request({
      url:'https://www.yunzhuke.net/api/activity/getDetail',
      method: 'GET',//方法分GET和POST，根据需要写
      data:{
        aid:that.aid,
      },
      header: {//定死的格式，不用改，照敲就好
        'Content-Type': 'application/json'
      },
      success: function (res) {//这里写调用接口成功之后所运行的函数
        console.log("详情获取成功")
        that.setData({
          qrcodeurl:res.data.data.fx_ewm,
          shareimg:res.data.data.img,
          shareimg2:res.data.data.img,
          background:res.data.data.imgs,
          phoneNumber:res.data.data.phone,
          lng:res.data.data.lng,
          lat:res.data.data.lat,
          detailimgs:res.data.data.detailimgs,
          resdata: res.data.data,//res.data就是你调出来的所有数据（当然也可以在这里面自定义想要调用的数据），然后把值赋给resdata，之后对resdata进行处理即可，具体见wxml
        })

      },
      fail: function (res) {//这里写调用接口失败之后所运行的函数

      }
    })
  },

  radioChange(e) {
    const items = this.data.items
    for (let i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value === e.detail.value
    }

    this.setData({
      items
    })
  },

    //套餐选择
    shareButton: function(e) {
      this.setData({
        shareModalStatus: false,
        maskHidden: false,
      })
    },

    //保存图片
     //套餐选择
     download: function(e) {
      //判断用户是否授权
      let that = this
      let shareInfo = {
        headerImg: 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132',
        bgImg: '/activity/images/home.png',
        qrcode: 'tempfilepath'
      }
      wx.getSystemInfo({
        success (res) {
          // 通过像素比计算出画布的实际大小（330x490）是展示的出来的大小
          that.setData({
            width: 330 * res.pixelRatio,
            height: 490 * res.pixelRatio
           });
        }
      })
      // wx.navigateTo({
      //   url: '/pages/index/index?shareInfo=' + JSON.stringify(shareInfo)
      // })
    },

  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
     //用户按了允许授权按钮
     var that = this;
     // 获取到用户的信息了，打印到控制台上看下
    //  console.log("用户的信息如下：");
     console.log(e.detail.userInfo);
     //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
   
     that.setData({
      isHide: false
     });
    } else {
     //用户按了拒绝按钮
     wx.showModal({
      title: '警告',
      content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
      showCancel: false,
      confirmText: '返回授权',
      success: function(res) {
       // 用户没有授权成功，不需要改变 isHide 的值
       if (res.confirm) {
        console.log('用户点击了“返回授权”');
       }
      }
     });
    }
   },

  
  getUserProfile() {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          avatarUrl: res.userInfo.avatarUrl,
          userInfo: res.userInfo,
          hasUserInfo: true,
        })
      }
    })
  },
  //拨打电话
  freeTell: function(){
    
    wx.makePhoneCall({

      phoneNumber: this.data.phoneNumber,

    })

  },
    //分享弹框
  share: function(){
    var that = this;
    //确认是否授权
    that.setData({
      shareModalStatus: true
     });
    
  },
    //分享弹框
    home: function(){
      var that = this;
      //确认是否授权
      wx.switchTab({
        url: '/pages/index/index',
      })
    },
   //取消分享弹框
   cancel: function(){
    var that = this;
    that.setData({
      shareModalStatus: false,
      maskHidden: false,
     });
    
  },

  //购买弹框
  btnclick: function(){
    var that = this;
    //确认是否授权
    that.setData({
      showModalStatus: true
     });
    
  },

  //立即购买操作
  buy: function(){

    var that = this;
    var uid = wx.getStorageSync("uid");
    if (!uid) {
        wx.navigateTo({
          url: '../activitylogin/activitylogin?aid='+that.aid
        })
        return
    }
 

    //创建订单
    wx.request({
      url:'https://www.yunzhuke.net/api/activity/createActivityOrder',
      method: 'GET',
      data:{
        aid:that.aid,
        uid:uid
      },
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if(res.data.code == 0){
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
        }else{
          let prepay_id = res.data.data.prepay_id  //预支付id
          let order_no = res.data.data.order_no    //订单号
          let timeStamp = String(res.data.data.timeStamp)  //服务器端返回的时间戳，必须强转字符串，微信要求的
          let nonceStr = res.data.data.nonce_str //服务器返回的随机字符串
          let packageres = 'prepay_id=' + res.data.data.prepay_id
          let paySign = res.data.data.paySign //支付签名

          // 拉起微信支付
          wx.requestPayment({
            'timeStamp': timeStamp,
            'nonceStr': nonceStr,
            'package': packageres,
            'signType': 'MD5',
            'paySign': paySign,
            success: function (res) {
              //接口调用成功的回调函数
              console.log('支付success')
              console.log(res.errMsg)
              if (res.errMsg == 'requestPayment:ok'){
                setTimeout(() => {
                  wx.showToast({
                    title: '支付成功',
                    icon: "none",
                  });
                  setTimeout(() => {
                    wx.reLaunch({
                     // url: '../refund/refund?ordernum=' + order_no
                     url:'/pages/index/index',
                    })
                  }, 2000)
                }, 0);
              }
           

            },
            fail: function (res) {
              console.log(8)
              console.log(res)
              wx.showToast({
                title: '支付失败',
                icon: 'none',
                duration: 3000
              })
              //接口调用失败的回调函数
            },
            complete: function (res) {
              console.log(9)
              console.log(res)
              //接口调用结束的回调函数（调用成功、失败都会执行）
            }
          })
        }
        }
        

    })


 
 

  },

  myCatchTouch: function(){
    var that = this;
    that.setData({
      showModalStatus: false,
      maskHidden: true,
      shareModalStatus: false
     });
    },
  openLocation: function () {
    wx.openLocation({
    
    latitude: parseFloat(this.data.lat),
    
    longitude: parseFloat(this.data.lng),
    
    })
    
    },

    onShareAppMessage: function(res) {
      let that = this;
      console.log(that.data.resdata.title);
      console.log("发送朋友");
      // console.log('主图------------->',that.data.goodsObj.MainImages)
      return {
        title: that.data.resdata.title,
        path: '/activity/pages/activity/activity?scene='+that.aid,
        success: function(res) {
          that.setData({
            showModalStatus: false,
            maskHidden: false,
            shareModalStatus: false
           });
        },
        fail: function(res) {
          that.setData({
            showModalStatus: false,
            maskHidden: false,
            shareModalStatus: false
           });
        }
      }
  
    },

    onShareTimeline: function(res){
      let img = this.data.shareimg2;  //分享的时候展示的图片
      var goods_id = this.aid;
      var query = {
        scene: goods_id
      };
      console.log(img)
      return {
        title: this.data.resdata.title,
        query: query,
        imageUrl:img   //图片地址
      }
    },
 

    onShareTimeline2: function (res) {
      let that = this;
      var share_title =  that.data.resdata.title;
      var goods_id = that.aid;
      let shareImg = this.data.shareimg2;  //分享的时候展示的图片
      console.log('分享id：' + goods_id);
      var query = {
        scene: goods_id
      };
      query = JSON.stringify(query.data);  //解析一下query
      return {
        title: share_title,
        query: query,
        imageUrl: shareImg ? shareImg : that.data.share_image,
        success: function (res) {
          that.setData({
            showModalStatus: false,
            maskHidden: false,
            shareModalStatus: false
           });
        },
        fail: function (res) {
          that.setData({
            showModalStatus: false,
            maskHidden: false,
            shareModalStatus: false
           });
        }
      }
    },

  onGetUserInfo: function(e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo,
        hasUserInfo: true,
      })
    }
  },
 
  //点击保存到相册
  baocun: function () {
    console.log("保存海报")
    var that = this
    console.log(that.data.imagePath)
    wx.downloadFile({
      url: that.data.imagePath,
      success:function(res){
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success:function(res2){
              wx.showModal({
                content: '海报已保存到相册',
                showCancel: false,
                confirmText: '确定',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击确定');
                    that.setData({
                      maskHidden: false,
                      shareModalStatus: false
                    });
                    /* 该隐藏的隐藏 */
                    that.setData({
                      maskHidden: false
                    })
                  }
                }, fail: function (res) {
                  console.log(11111)
                }
              })
            }
          })
       
        }else{
          wx.showToast({
            title:"海报保存失败",
            icon: 'none',
            duration: 2000
          });
          return
        }
      
      },
      fail:function(err){
        wx.showToast({
          title:"海报下载失败",
          icon: 'none',
          duration: 2000
        });
        return
      }
    })

  },
  //点击生成
  formSubmit: function (e) {
    var that = this;
    var uid = wx.getStorageSync("uid");
    if (uid) {
        console.log("登陆")
    }else{
        console.log('no')
        wx.navigateTo({
          url: '../activitylogin/activitylogin?aid='+that.aid
        })
        return
    }

    wx.showToast({
      title: '海报生成中...',
      icon: 'loading',
      duration: 10000
    });
    //调用生成海报接口
    wx.request({
      url:'https://www.yunzhuke.net/api/activity/rePoster',
      //url:'http://local.minshuv2.com/api/activity/rePoster',
      method: 'GET',//方法分GET和POST，根据需要写
      data:{
        uid:uid,
        aid:that.aid,
      },
      header: {//定死的格式，不用改，照敲就好
        'Content-Type': 'application/json'
      },
      success: function (res) {//这里写调用接口成功之后所运行的函数
          if(res.data.code == 1){
            wx.hideToast()
            that.setData({
              imagePath: res.data.data,
              maskHidden:true,
              shareModalStatus:true,
            });



          }else{
            //海报失败 提示
            setTimeout(function () {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 2000
              });
            }, 1000)
          }

      },
      fail: function (res) {//这里写调用接口失败之后所运行的函数

      }
    })
 
 
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getUserInfo({
      success: res => {
        console.log(res.userInfo, "huoqudao le ")
        this.setData({
          name: res.userInfo.nickName,
        })
      }
    })
  },


 

})
